package com.stn.zjx.givingtreasure.activity.bi;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.EthTransferDetailDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.EthNetImpl;
import com.stn.zjx.givingtreasure.utils.StatusBarUtil;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;
import com.vondear.rxtools.RxImageTool;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class EthTransferDetailActivity extends BaseActivity {
    private static final int PRC_PHOTO_PICKER = 1010;
    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.share_bt)
    TextView shareBt;
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.value)
    TextView value;
    @BindView(R.id.from_address)
    TextView fromAddress;
    @BindView(R.id.to_address)
    TextView toAddress;
    @BindView(R.id.contract_address_tv)
    TextView contractAddressTv;
    @BindView(R.id.contract_address_layout)
    LinearLayout contractAddressLayout;
    @BindView(R.id.max_gas_price)
    TextView maxGasPrice;
    @BindView(R.id.tx_hash)
    TextView txHash;
    @BindView(R.id.max_step)
    TextView maxStep;
    @BindView(R.id.step_num)
    TextView stepNum;
    @BindView(R.id.step)
    LinearLayout step;
    @BindView(R.id.send_time)
    TextView sendTime;
    @BindView(R.id.block_num)
    TextView blockNum;
    @BindView(R.id.extra)
    TextView extra;
    @BindView(R.id.rootView)
    NestedScrollView rootView;


    private String data = "";

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        data = getIntent().getStringExtra("txHash");
        if (!TextUtils.isEmpty(data)) {
            initData(data);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eth_transfer_detail);
        StatusBarUtil.setImmersiveStatusBar(this, false);
        ButterKnife.bind(this);
        initComponent();
    }

    @OnClick({R.id.back_bt, R.id.share_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.share_bt:
                Bitmap bitmap = ToolsUtils.getBitmapByView(rootView);
                savetoImg(bitmap);
                break;
        }
    }

    @AfterPermissionGranted(PRC_PHOTO_PICKER)
    public void savetoImg(Bitmap bitmap) {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            showLoading();
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File file = new File(Environment.getExternalStorageDirectory().getPath(), getString(R.string.app_name));
            if (!file.exists()) {   //判断文件夹是否存在，不存在则创建
                file.mkdirs();
            }
            String fileName = "";
            fileName = UUID.randomUUID().toString().substring(0, 4) + ".jpg";
            String com_file = file.getPath() + "/" + fileName;
            boolean isSuccess = RxImageTool.save(bitmap, com_file, Bitmap.CompressFormat.JPEG);
            if (isSuccess) {
                // 把文件插入到系统图库
                try {
                    String s = MediaStore.Images.Media.insertImage(getContentResolver(), com_file, fileName, "分享图片");

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + com_file));
                // 通知图库更新
                sendBroadcast(intent);

                ToolsUtils.shareImage(this, new File(com_file));
            } else {
                showToast("save error");
            }
            dissmissLoading();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.request_perssion_desc), PRC_PHOTO_PICKER, perms);
        }
    }

    public void initData(String txHash) {
        EthNetImpl
                .query_transfer_txhash(txHash, txHash + "_query_transfer_txhash", new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            initDetail(response.body());
                        }

                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful() && !isFinishing()) {
                            initDetail(response.body());
                        }
                    }
                });
    }

    @SuppressLint("SetTextI18n")
    public void initDetail(String body) {
        EthTransferDetailDomain domain = new Gson().fromJson(body, EthTransferDetailDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                switch (domain.getData().getStatus()) {
                    case 0:
                        iv.setImageResource(R.mipmap.eth_transfer_detail_loading);
                        status.setTextColor(ActivityCompat.getColor(this, R.color.default_orange));
                        status.setText(getString(R.string.transferLoading));
                        break;
                    case 1:
                        iv.setImageResource(R.mipmap.eth_transfer_detail_success);
                        status.setTextColor(ActivityCompat.getColor(this, R.color.default_green));
                        status.setText(getString(R.string.success));
                        break;
                    case 2:
                        iv.setImageResource(R.mipmap.eth_transfer_detail_fail);
                        status.setTextColor(ActivityCompat.getColor(this, R.color.default_red));
                        status.setText(getString(R.string.fail));
                        break;
                }
                value.setText(domain.getData().getAmount() + domain.getData().getSymbol().toLowerCase());
                fromAddress.setText(domain.getData().getFromAddress());
                toAddress.setText(domain.getData().getToAddress());
                maxGasPrice.setText(domain.getData().getGasPrice()+"ether");
                txHash.setText(domain.getData().getTxHash());
                maxStep.setText(domain.getData().getGasLimit());
                if (TextUtils.isEmpty(domain.getData().getContractAddress())) {
                      contractAddressLayout.setVisibility(View.GONE);
                } else {
                    contractAddressTv.setText(domain.getData().getContractAddress());
                    contractAddressLayout.setVisibility(View.VISIBLE);
                }
                if (TextUtils.isEmpty(domain.getData().getGasUsed())) {
                    stepNum.setText(getString(R.string.loading_calculation));
                } else {
                    stepNum.setText(domain.getData().getGasUsed());
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sendTime.setText(sdf.format(new Date(Long.parseLong(domain.getData().getSendTime()))));
                if (TextUtils.isEmpty(domain.getData().getBlockNumber())) {
                    blockNum.setText(getString(R.string.loading_calculation));
                } else {
                    blockNum.setText(domain.getData().getBlockNumber());
                }
                if(TextUtils.isEmpty(domain.getData().getExtra())){
                   extra.setTextColor(ActivityCompat.getColor(this,R.color.gray));
                    extra.setText(getString(R.string.no_remark_tip));
                }else{
                    extra.setTextColor(ActivityCompat.getColor(this,R.color.font_black));
                    extra.setText(domain.getData().getExtra());
                }
                break;
        }
    }
}
